
import csv
import re

import objects as obj
from exception import *
from log import *
from utils import *

class CSVData:

    def __init__(self, cfg, infile):
	self.rdr = csv.reader(open(infile, "rb"), dialect="excel-tab")
	self.cfg = cfg

    def parse(self, delim):
	varset = {}
	
	for row in self.rdr:
	    if not row:
		continue
	    key = unicode(row[0], errors='ignore')
	    row.remove(key)
	    try:
	        lines = self.parseRow(row, delim)
	        if len(lines):
		    peaks = obj.lines2peaks(lines, self.cfg.debug)
		    varset[key] = obj.Var(key, peaks)
	    except ValueError, e:
		raise ValueError("Error parsing %s" % key)
	
	return varset

    def parseRow(self, row, delim):
	lines = []
	for coords in row:
	    if not coords:
		continue
	    coords = re.sub(r'\s+', '', coords)
	    coords = re.split(delim, coords)
	    p0 = obj.Point(float(coords[0]), float(coords[1]))
	    p1 = obj.Point(float(coords[2]), float(coords[3]))
	    lines.append( obj.Line(p0, p1) )
	return lines


class CSVVars:

    def __init__ (self, cfg, infile):
	self.rdr = csv.reader(open(infile, "rb"), dialect="excel-tab")
	self.cfg = cfg

    def parse(self, delim):
	vset = {}
	vlist = {}
	logger = Logger()
	
	for row in self.rdr:
	    if not row:
		continue
	    if len(row) < 2:
		s = 'Error input data: %s' % repr(row)
		if self.cfg.ignore:
		    logger.warning(s)
		else:
		    raise Handled(s)
		continue
		
	    var = unicode(row[0], errors='ignore')
	    name = Utils.decode(row[1]) #unicode(row[1], errors='ignore')
	    parent = ''
	    if len(row) > 2:
		parent = unicode(row[2], errors='ignore')
		
		if not parent in vlist:
		    vlist[parent] = []
		vlist[parent].append(var)
	    
	    vset[var] = {'var': var, 'name': name, 'parent': parent, 'val': 0.0}
	
	return {'list' : vlist, 'set': vset}
